package com.ganbo.pattern.prototype;

import java.io.*;

/**
 * 利用序列化实现深克隆工具类
 *
 * @Author: ganbo
 * @Date: 2020/6/9 15:49
 */
public class CloneUtil {

    public static <T extends Serializable> T clone(T o) {
        T cloneObj = null;
        try {
            //写入字节流
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ObjectOutputStream obs = new ObjectOutputStream(out);
            obs.writeObject(o);
            obs.close();

            //分配内存，写入原始对象，生成新对象
            ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(ios);
            //返回生成的新对象
            cloneObj = (T) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cloneObj;
    }
}
